package com.quick.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.quick.Quick;
import com.quick.annotation.IgnoreToken;
import com.quick.config.QuickProperties;
import com.quick.exception.QuickStateEnum;
import com.quick.spring.SpringUtil;
import com.quick.util.QuickTool;
import com.quick.util.TokenUtil;


public class LoginInterceptor extends HandlerInterceptorAdapter{

	private static final Logger  log = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		Quick  quick = SpringUtil.getBean(Quick.class);
		Map<String, Object> develop = quick.getDevelop();
		QuickProperties basis = (QuickProperties) develop.get("basis");
		if(handler instanceof HandlerMethod) {
			 HandlerMethod handlerMethod = (HandlerMethod) handler;
	         Method method = handlerMethod.getMethod();
	         IgnoreToken checkToken = method.getAnnotation(IgnoreToken.class);
	         if(ObjectUtils.isEmpty(checkToken)){
	        	String token  = request.getHeader(basis.getTokenKey());
	     		QuickTool.isNullBlank(token, QuickStateEnum.TOKEN_NOT_NULL);
	     		log.info("登录前置拦截器 preHandle");
	     		TokenUtil.check(token);
	         }
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		log.info("登录后置拦截器 postHandle");
		super.postHandle(request, response, handler, modelAndView);
	}

}
